{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import Spider\n",
    "\n",
    "def highlight(text: str, keyword: str):\n",
    "    idx = text.lower().find(keyword.lower())\n",
    "    result = text\n",
    "    if idx >= 0:\n",
    "        ori_word = text[idx:idx+(len(keyword))]\n",
    "        result = text.replace(ori_word, f'*{ori_word}*')\n",
    "    return result\n",
    "\n",
    "def score(item, keyword: str):\n",
    "    title_score = item[1].lower().count(keyword.lower())\n",
    "    content_score = item[2].lower().count(keyword.lower())\n",
    "    score_result = title_score * 5 + content_score * 3\n",
    "    return score_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "outputs": [],
   "source": [
    "import jieba\n",
    "\n",
    "class MySearcherC6V0:\n",
    "    \"\"\"\n",
    "    第五次课升级的搜索类版本：\n",
    "    1、增加初始化参数scale，用于倍增文档集\n",
    "    2、增加缓存机制，避免重复匹配相同关键词\n",
    "    3、增加线下缓存预填充机制，用猜测得到的用户查询词预填充\n",
    "    4、用文档分词得到的词表进行缓存预填充\n",
    "    \"\"\"\n",
    "    def __init__(self, scale: int=1):\n",
    "        self.docs = list()\n",
    "        self.load_data()\n",
    "        if scale > 1:\n",
    "            self.docs *= scale  # 文档规模倍增，用于测试搜索速度\n",
    "        self.cache = dict()\n",
    "        self.vocab = set()\n",
    "        self.build_cache()\n",
    "\n",
    "    def load_data(self, data_file_name='./news_list.pkl'):\n",
    "        if os.path.exists(data_file_name):\n",
    "            self.docs = Spider.pickle_load(data_file_name)\n",
    "        else:\n",
    "            Spider.pickle_save(data_file_name)\n",
    "            self.docs = Spider.pickle_load(data_file_name)\n",
    "\n",
    "    def search(self, keyword):\n",
    "        keyword = keyword.lower()\n",
    "        if keyword not in self.cache:\n",
    "            count = 0\n",
    "            sorted_result = list()\n",
    "            for item in self.docs:\n",
    "                if keyword in (item[1] + item[2]).lower():\n",
    "                    sorted_result.append([count, score(item, keyword), item[1]])\n",
    "                count += 1\n",
    "            sorted_result.sort(key=lambda x: x[1], reverse=True)\n",
    "            self.cache[keyword] = sorted_result\n",
    "        else:\n",
    "            sorted_result = self.cache[keyword]\n",
    "        return sorted_result\n",
    "\n",
    "    def render_search_result(self, keyword):\n",
    "        count = 0\n",
    "        for item in self.search(keyword):\n",
    "            count += 1\n",
    "            print(f'{count}[{item[1]}] {highlight(self.docs[item[0]][1], keyword)}')\n",
    "\n",
    "    def build_cache(self):\n",
    "        \"\"\"用分词（用文档过滤词库）的方式初始化缓存\"\"\"\n",
    "        for doc in self.docs:\n",
    "            for word in jieba.cut(doc[1]+' '+doc[2], cut_all=True):\n",
    "                self.search(word)\n",
    "                self.vocab.add(word)\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 1min 15s\n"
     ]
    }
   ],
   "source": [
    "%time searcher_v0 = MySearcherC6V0()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "outputs": [],
   "source": [
    "class MySearcherC6V1(MySearcherC6V0):\n",
    "    \"\"\"\n",
    "    避免相同词重复预热\n",
    "    \"\"\"\n",
    "    def build_cache(self):\n",
    "        word_set = set()\n",
    "        for doc in self.docs:\n",
    "            for word in jieba.cut(doc[1]+' '+doc[2]):\n",
    "                if word not in word_set:\n",
    "                    self.search(word)\n",
    "                    self.vocab.add(word)\n",
    "                    word_set.add(word)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 1min 7s\n"
     ]
    }
   ],
   "source": [
    "%time searcher_v1 = MySearcherC6V1()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "outputs": [],
   "source": [
    "class MySearcherC6V2(MySearcherC6V1):\n",
    "    \"\"\"\n",
    "    尽量减少lower运行次数\n",
    "    \"\"\"\n",
    "    def __init__(self, scale: int=1):\n",
    "        self.docs = list()\n",
    "        self.load_data()\n",
    "        if scale > 1:\n",
    "            self.docs *= scale  # 文档规模倍增，用于测试搜索速度\n",
    "        self.cache = dict()\n",
    "        self.vocab = set()\n",
    "        self.lower_preprocess()\n",
    "        self.build_cache()\n",
    "\n",
    "    def search(self, keyword):\n",
    "        keyword = keyword.lower()\n",
    "        if keyword not in self.cache:\n",
    "            count = 0\n",
    "            sorted_result = list()\n",
    "            for item in self.docs:\n",
    "                if keyword in item[3]:\n",
    "                    sorted_result.append([count, score(item, keyword), item[1]])\n",
    "                count += 1\n",
    "            sorted_result.sort(key=lambda x: x[1], reverse=True)\n",
    "            self.cache[keyword] = sorted_result\n",
    "        else:\n",
    "            sorted_result = self.cache[keyword]\n",
    "        return sorted_result\n",
    "\n",
    "    def lower_preprocess(self):\n",
    "        for doc_id in range(len(self.docs)):\n",
    "            self.docs[doc_id].append(\n",
    "                (self.docs[doc_id][1] + ' ' + self.docs[doc_id][2]).lower())\n",
    "\n",
    "    def simple_test(self):\n",
    "        assert(len(self.search('tiktok')) > 1)\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 10.2 s\n"
     ]
    }
   ],
   "source": [
    "%time searcher_v2 = MySearcherC6V2()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "outputs": [],
   "source": [
    "class MySearcherC6V3(MySearcherC6V2):\n",
    "    \"\"\"\n",
    "    用文档刷词构建缓存\n",
    "    \"\"\"\n",
    "    def build_cache(self):\n",
    "        \"\"\"用分词（用文档过滤词库）的方式初始化缓存\"\"\"\n",
    "        doc_id = 0\n",
    "        for doc in self.docs:\n",
    "            doc_word_set = set()\n",
    "            for word in jieba.cut(doc[3]):\n",
    "                if word not in doc_word_set:\n",
    "                    result_item = [doc_id, score(doc, word), doc[1]]\n",
    "                    if word not in self.cache:\n",
    "                        self.cache[word] = [result_item]\n",
    "                    else:\n",
    "                        self.cache[word].append(result_item)\n",
    "                self.vocab.add(word)\n",
    "                doc_word_set.add(word)\n",
    "            doc_id += 1\n",
    "        for word in self.cache:\n",
    "            self.cache[word].sort(key=lambda x: x[1], reverse=True)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 4.4 s\n"
     ]
    }
   ],
   "source": [
    "%time searcher_v3 = MySearcherC6V3()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "outputs": [],
   "source": [
    "searcher_v3.simple_test()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "outputs": [],
   "source": [
    "class MySearcherC6V4(MySearcherC6V3):\n",
    "    \"\"\"\n",
    "    去掉search里的文档扫描过程\n",
    "    \"\"\"\n",
    "    def search(self, keyword):\n",
    "        keyword_l = keyword.lower()\n",
    "        if keyword_l in self.cache:\n",
    "            sorted_result = self.cache[keyword_l]\n",
    "        else:\n",
    "            sorted_result = []\n",
    "        return sorted_result"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 4.57 s\n"
     ]
    }
   ],
   "source": [
    "%time searcher_v4 = MySearcherC6V4()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}